package com.gitee.feizns.quickstart.web.advice;

import com.gitee.feizns.quickstart.domain.vo.Ret;
import com.gitee.feizns.quickstart.jackson.Val;
import com.gitee.feizns.quickstart.web.WebUtils;
import com.jayway.jsonpath.JsonPath;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全球响应建议
 * @author feizns
 * @since 2024/12/16
 */
@RestControllerAdvice
public class JsonPathFilterResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    /**
     * jsonpath 过滤器参数名称
     */
    public static final String jsonpathFilterRootParameterName = "jpf";

    @Override
    public boolean supports(@NonNull MethodParameter returnType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, @NonNull MethodParameter returnType, MediaType selectedContentType, @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if ( selectedContentType.isCompatibleWith(MediaType.APPLICATION_JSON) ) {
            String jsonpath = WebUtils.getReq().getParameter(jsonpathFilterRootParameterName);
            if ( StringUtils.hasText(jsonpath) && body instanceof Ret )
                return Val.of(body).find(JsonPath.compile(jsonpath));
        }
        return body;
    }

}
